package com.aca.market.util;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class JsonUtils {

    private static Logger logger = LoggerFactory.getLogger(JsonUtils.class);

//    public static ObjectMapper mapper = new ObjectMapper();
    public static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        mapper.registerModule(new JavaTimeModule());
        //(yml里改了)所有日期都统一为以下样式：yyyy-MM-dd HH:mm:ss
        //mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    public static String toJSONString(Object object) {
        String result = "";
        try {
            result = mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static <T> T toObject(String json, Class<T> clazz) {
        T result = null;
        try {
            result = mapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static <T> List toArray(String json, Class<T> clazz) {
        try {
            return (List) mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (JsonParseException e) {
            logger.error("decode(String, JsonTypeReference<T>)", e);
            e.printStackTrace();
        } catch (JsonMappingException e) {
            logger.error("decode(String, JsonTypeReference<T>)", e);
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("decode(String, JsonTypeReference<T>)", e);
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, Object> toObject(String json) {
        return toObject(json, Map.class);
    }

    public static List<Map<String, Object>> toArray(String json) {
        return toArray(json, Map.class);
    }

    public static void main(String[] args) {
        // 字符串转List<Map>
        String json = "[{\"id\":1,\"name\":\"张三\"},{\"id\":2,\"name\":\"李四\"}]";
        List<Map<String,Object>> array = toArray(json);
        System.out.println(array);

        // 字符串转Map
        json = "{\"id\":1,\"name\":\"张三\"}";
        Map<String,Object> map = toObject(json);
        System.out.println(map);

        // 各种对象转JSON字符串
        json = toJSONString(array);
        System.out.println(json);
    }
}
